package com.hxkj.client.service.taglib.directive;

import com.hxkj.client.service.ArticleServiceClient;
import com.hxkj.domain.context.EnvironmentContextHolder;
import com.hxkj.domain.po.Article;
import com.hxkj.domain.po.WebsiteAddr;
import com.platform.common.domain.result.ResultDataStruct;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.hxkj.client.service.taglib.config.LableConstant.CMS_RECOMMENDATIONARTICLE;

/**
 * 子定义标签
 * 外汇网的相关推荐文章,查找的是相同tags的文章,不足十篇的用当前分类的补足十篇
 *
 * @author chenfangzhou 2018/09/14
 */
@Component
@Slf4j
public class RecommendationArticleDirective extends AbstractDirective {
    @Autowired
    private ArticleServiceClient articleServiceClient;

    //站点id
    private static final String SITE_ID = "siteId";
    //文章id
    private static final String ARTICLE_ID = "articleId";
    //分类id
    private static final String COLUMN_ID = "columnId";
    //排序字段
    private static final String SORT = "sort";
    //获取文章的条数
    private static final String COUNT = "count";

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        try {
            Long siteId = getLong(SITE_ID, params) == null ? (Long) getCustomAttrbute(env, SITE_ID) : getLong(SITE_ID, params);
            Long articleId = getLong(ARTICLE_ID, params) == null ? getArticleId(env) : getLong(ARTICLE_ID, params);
            Long columnId = getLong(COLUMN_ID, params) == null ? getColumnId(env) : getLong(COLUMN_ID, params);
            String sort = StringUtils.isBlank(getString(SORT, params)) ? "heat" : getString(SORT, params);
            Integer count = getInt(COUNT, params) == null ? 10 : getInt(COUNT, params);
            String note = super.getNote(env);
            List<Article> recommendationArticles;
            if (columnId == null) {
                log.debug("获取环境的分类id为空!");
                recommendationArticles = new ArrayList<>();
            } else {

                // 找出该篇文章的tags
                Article article = new Article();
                article.setSiteId(siteId);
                article.setArticleId(articleId);
                ResultDataStruct<Article> resultArticle = articleServiceClient.getArticle(article);

                // 没有获取到该篇文章的tags,直接取同分类下的十篇文章
                if (null == resultArticle || null == resultArticle.getData() || StringUtils.isBlank(resultArticle.getData().getTags())) {
                    recommendationArticles = new ArrayList<>();
                } else {

                    Article article_ = new Article();
                    article_.setArticleId(articleId);
                    article_.setSiteId(siteId);
                    article_.setTags(resultArticle.getData().getTags());
                    article_.setSort(sort);
                    article_.setCount(count);
                    recommendationArticles = articleServiceClient.getRecommendationArticle(article_);
                }

                //如果不足指定篇数的,用同类型的文章补足
                if (recommendationArticles.size() < count) {
                    Article article_ = new Article();
                    article_.setSiteId(siteId);
                    article_.setArticleId(articleId);
                    article_.setColumnId(columnId);
                    article_.setSort(sort);
                    article_.setCount(count - recommendationArticles.size());
                    List<Article> correlationArticle = articleServiceClient.getCorrelationArticle(article_);
                    recommendationArticles.addAll(correlationArticle);
                }
                WebsiteAddr webSiteAddr = getWebSiteAddr(siteId);
                if (StringUtils.isNotBlank(note)) {
                    for (Article arc : recommendationArticles) {
                        arc.setManuscriptPath(webSiteAddr.getIpAdd() + arc.getManuscriptPath());
                    }
                }else {
                    Map<String, Object> enviroment = EnvironmentContextHolder.getEnvironment();
                    Map<Long, String> siteCtxMap = (Map<Long, String>) enviroment.get("siteCtxMap");
                    String urlContext = siteCtxMap.get(siteId);
                    // 静态文件文章链接加前缀
                    for (Article item : recommendationArticles) {
                        if(StringUtils.isNotBlank(urlContext)) {
                            item.setManuscriptPath(urlContext + item.getManuscriptPath());
                        }
                    }
                }
            }

            env.setVariable("recommendationArticles", DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(recommendationArticles));

            String userToken = super.getUserToken(env);
            if (body != null) {
                if (StringUtils.isEmpty(note)) {
                    body.render(env.getOut());
                } else {
                    Map<String, String> maps = new LinkedHashMap<>();

                    maps.put(CMS_RECOMMENDATIONARTICLE, "");
                    maps.put(SITE_ID, String.valueOf(getLong(SITE_ID, params)));
                    maps.put(ARTICLE_ID, String.valueOf(getLong(ARTICLE_ID, params)));
                    maps.put(SORT, String.valueOf(getLong(SORT, params)));
                    maps.put(COUNT, String.valueOf(getInt(COUNT, params)));
                    try {
                        super.print(body, maps, env, userToken, params);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                log.debug("相关推荐文章所在模板至少要加一个空格");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
